package xyz.zyl2020.websocket.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean;
import xyz.zyl2020.websocket.handler.ChatWebSocketHandler;
import xyz.zyl2020.websocket.interceptor.ChatHandshakeInterceptor;

/**
 * WebSocket配置类
 *
 * @author ZhuYinglong
 * @date 2020/8/13 0013
 */
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    /**
     * 用于将WebSocket处理程序映射到特定URL
     *
     * @param registry
     */
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(chatWebSocketHandler(), "chat") // 添加消息处理器
                .addInterceptors(chatHandshakeInterceptor()) // 添加握手拦截器
                .setAllowedOrigins("*"); // 设置跨域
    }

    /**
     * 自定义消息处理器
     *
     * @return
     */
    @Bean
    public ChatWebSocketHandler chatWebSocketHandler() {
        return new ChatWebSocketHandler();
    }

    /**
     * 自定义消息拦截器
     *
     * @return
     */
    @Bean
    public ChatHandshakeInterceptor chatHandshakeInterceptor() {
        return new ChatHandshakeInterceptor();
    }

    /**
     * 其他配置，如session空闲失效时间，消息缓冲区大小
     *
     * @return
     */
    @Bean
    public ServletServerContainerFactoryBean createWebSocketContainer() {
        ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
        container.setMaxTextMessageBufferSize(8192);
        container.setMaxSessionIdleTimeout(10 * 60 * 1000L);
        return container;
    }

}
